package com.software.comment.contorller;



import com.software.comment.mapper.LikeMapper;
import com.software.comment.pojo.Like;
import com.software.comment.pojo.Result;
import com.software.comment.service.LikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 浦慧慧
 * @since 2024/12/15 11.34
 * @version 1.0
 */
@RestController
@RequestMapping("/likes")
public class LikeController {

    @Autowired
    private LikeService likeService;

    @Autowired
    private LikeMapper likeMapper;

    /**
     * 添加或修改点赞
     *
     * @param commentId 评论id
     * @param username  用户名
     * @return 点赞结果 1：点赞成功 0：取消点赞 2：点赞失败
     */
    @PostMapping("/{commentId}/{username}")
    public Result<String> like (@PathVariable Integer commentId , @PathVariable String username) {
        Boolean num = checkLike(commentId, username);
        if (num) {
            Integer isLikedInDB = likeService.selectLikeByCommentIdAndUsername(commentId, username);
            if(isLikedInDB>=0&&isLikedInDB<=1){
                likeService.toChangeLike(true, username, commentId);
            }
            if (isLikedInDB== 1) {
                return Result.success("1");
            } else {
                return Result.success("0");
            }
        } else {
            likeService.addlike(username, commentId);
            return Result.success("2");
        }
    }

    /**
     * 展示点赞
     *
     * @param taskid 任务id
     * @return 点赞列表
     */
    @GetMapping("/{taskid}")
    public Result<?> show(@PathVariable Integer taskid) {
        List<Like> like =likeService.showLikes(taskid);
        return Result.success(like);
    }

    /**
     * 是否点赞
     *
     * @param commentId 评论id
     * @param username  用户名
     * @return 点赞状态 1：已点赞 0：未点赞 -1：未登录
     * @throws Exception
     */
    @GetMapping("/{commentId}/{username}/islike")
    public Result<?> isLike(@PathVariable Integer commentId, @PathVariable String username) {
        Integer num=likeService.checkLike(commentId, username);
        System.out.println("返回的是否点赞 "+num);
        return Result.success(num);
    }

    /**
     * 查询点赞状态方法
     *
     * @param commentId
     * @param username
     * @return
     */
    public Boolean checkLike(Integer commentId,String username) {
        Integer count = likeService.countByCommentId(commentId,username);
        if (count==1) {
            return true;
        } else {
            return false;
        }
    }

}